﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.Mvc;
using SnippetBox.Core.Common.Extensions;
using SnippetBox.Core.Infrastructure;

namespace SnippetBox.Core.Data.Models {
    public class Category : IDeletable {
        public Category(string name) {
            Name = name;
            Slug = name.Slugify();
        }

        public Category() { }

        public Category(string name, Category parentCategory) {
            Name = name;
            ParentCategory = parentCategory;
            Slug = name.Slugify();
        }

        public int CategoryId { get; set; }
        [Required, MaxLength(100)]
        public string Name { get; set; }
        [MaxLength(200)]
        public string Slug { get; set; }
        public virtual Category ParentCategory { get; set; }
        public virtual ICollection<Category> ChildrenCategories { get; set; }
        public virtual ICollection<Snippet> Snippets { get; set; }
        public bool IsDeleted { get; set; }

        public string Link {
            get {
                UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
                return url.RouteUrl("Category-Details", new {
                    categoryId = CategoryId,
                    categorySlug = Slug,
                });
            }
        }


        /// <summary>
        /// Checks if logged in user can create snippets.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool CanCreate(User user) {
            if (user == null)
                return false;
            return user.IsInRole(Role.Editor) || Settings.Current.Permissions.AllowMembersToCreateSnippets;
        }
        
    }
}